package service

import (
	"errors"
	"go-ecommerce/internal/model"
	"gorm.io/gorm"
)

type PermissionTreeDTO struct {
	ID       uint64              `json:"id"`        // 权限ID
	Name     string              `json:"name"`      // 权限名称
	Code     string              `json:"code"`      // 权限标识码（唯一）
	ParentID uint64              `json:"parent_id"` // 父级权限ID
	Path     string              `json:"path"`      // 路径（用于前端路由）
	Method   string              `json:"method"`    // 请求方法
	Children []PermissionTreeDTO `json:"children"`
}

func GetPermissionList(db *gorm.DB) ([]PermissionTreeDTO, error) {
	var permissions []model.Permission

	err := db.Find(&permissions).Error

	if err != nil {
		return nil, err
	}
	// 转换为树结构
	tree := buildPermissionTree(permissions, 0)
	return tree, nil
}

func buildPermissionTree(permissions []model.Permission, parentID uint64) []PermissionTreeDTO {
	var tree []PermissionTreeDTO

	for _, permission := range permissions {
		if permission.ParentID == parentID {
			model := PermissionTreeDTO{
				ID:       permission.ID,
				Name:     permission.Name,
				Code:     permission.Code,
				ParentID: permission.ParentID,
				Method:   permission.Method,
				Children: buildPermissionTree(permissions, permission.ID),
			}
			tree = append(tree, model)
		}
	}
	return tree
}

func CreatePermission(db *gorm.DB, req model.Permission) error {
	var permission model.Permission
	//查看权限是否存在
	if err := db.Where("code = ?", req.Code).First(&permission).Error; err == nil {
		return errors.New("权限标识已经存储在")
	}
	return db.Create(&req).Error
}

func UpdatePermission(db *gorm.DB, id uint64, req model.Permission) error {
	var permission model.Permission
	if err := db.Where("id = ?", id).First(&permission).Error; err != nil {
		return errors.New("权限不存在")
	}

	// 用新的变量做唯一性校验
	var existCheck model.Permission
	if err := db.Where("code = ? AND id  <> ?", req.Code, id).First(&existCheck).Error; err == nil {
		return errors.New("该标识已经存在")
	} else if !errors.Is(err, gorm.ErrRecordNotFound) {
		return err
	}

	permission.Name = req.Name
	permission.Code = req.Code
	permission.Method = req.Method
	return db.Save(&permission).Error
}

func DeletePermission(db *gorm.DB, id uint64) error {
	var count int64
	db.Model(&model.Permission{}).Where("parent_id = ?", id).Count(&count)
	if count > 0 {
		return errors.New("请先删除子权限")
	}
	return db.Delete(&model.Permission{}, id).Error
}

// GetAdminPermissions 获取管理员拥有的所有权限（去重）
func GetAdminPermissions(db *gorm.DB, adminID uint) ([]model.Permission, error) {
	var roles []model.AdminRole
	err := db.Where("admin_id = ?", adminID).Find(&roles).Error
	if err != nil {
		return nil, err
	}

	var roleIDs []uint64
	for _, r := range roles {
		roleIDs = append(roleIDs, r.RoleID)
	}

	var permissionIDs []uint64
	err = db.Model(&model.RolePermission{}).Where("role_id IN ?", roleIDs).Pluck("permission_id", &permissionIDs).Error
	if err != nil {
		return nil, err
	}

	var permissions []model.Permission
	err = db.Where("id IN ?", permissionIDs).Find(&permissions).Error
	return permissions, err
}
